package com.durablemethods.futures.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.durablemethods.futures.client.NHLTrader;
import com.durablemethods.futures.client.NHLTraderService;
import com.google.appengine.api.rdbms.AppEngineDriver;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class NHLTraderServiceImpl  extends RemoteServiceServlet implements NHLTraderService{
	private static final String CONNECTION_STRING = "jdbc:google:rdbms://durablemethods.com:duravest:durable-futures-db";
	private static final long serialVersionUID = 8072110021394032354L;
	private static final Logger log = Logger.getLogger(NHLTraderServiceImpl.class.getName());
	@Override
	public NHLTrader getTraderWithGoogleAccount(String googleAccount) {
		NHLTrader returnTrader = new NHLTrader();
		returnTrader.setGoogleAccount(googleAccount);
		Connection c = null;
	      try {	    	 
			DriverManager.registerDriver(new AppEngineDriver());
			c = DriverManager.getConnection(CONNECTION_STRING,"root","");
			PreparedStatement ps = c.prepareStatement("Select * from durable_futures.TRADERS where google_account=?");
			ps.setString(1, googleAccount);
			ResultSet rs = ps.executeQuery();
			while (rs.next()){
				returnTrader.setAlias(rs.getString("alias"));
				returnTrader.setTwitterHandle(rs.getString("twitter_handle"));
				returnTrader.setGuarantor(rs.getString("guarantor"));
				returnTrader.setAuthorized(true);
			}
			ps.close();
			c.close();
		} catch (SQLException e) {
			log.info(e.getMessage());
			e.printStackTrace();
		}
		return returnTrader;
	}

	@Override
	public List<NHLTrader> getAuthorizedTraders() {
		return null;
	}

	@Override
	public List<NHLTrader> getAllTraders() {
		List<NHLTrader> returnList = new ArrayList<NHLTrader>();
		
		Connection c = null;
	      try {	    	 
			DriverManager.registerDriver(new AppEngineDriver());
			c = DriverManager.getConnection(CONNECTION_STRING,"root","");
			PreparedStatement ps = c.prepareStatement("Select * from durable_futures.TRADERS ");
			ResultSet rs = ps.executeQuery();
			while (rs.next()){
				NHLTrader returnTrader = new NHLTrader();
				returnTrader.setGoogleAccount(rs.getString("google_account"));
				returnTrader.setAlias(rs.getString("alias"));
				returnTrader.setTwitterHandle(rs.getString("twitter_handle"));
				returnTrader.setGuarantor(rs.getString("guarantor"));
				returnTrader.setAuthorized(true);
				returnList.add(returnTrader);
			}
			ps.close();
			c.close();
		} catch (SQLException e) {
			log.info(e.getMessage());
			e.printStackTrace();
		}
		return returnList;
	}

}
